<template>
  <div class="user-management-container">
    <PageHeader title="用户管理">
      <template #actions>
        <el-button type="primary" @click="navigateToRoleManagement" class="role-btn">
          <el-icon><Setting /></el-icon>
          角色管理
        </el-button>
        <el-button type="primary" @click="showAddUserDialog">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </template>
    </PageHeader>

    <main class="user-management-content">
      <!-- 搜索和筛选区域 -->
      <el-card class="filter-card">
        <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名、姓名或邮箱"
          clearable
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="roleFilter" placeholder="角色筛选" clearable @change="handleSearch" class="filter-select">
          <el-option
            v-for="role in roles"
            :key="role.name"
            :label="role.name"
            :value="role.name"
          />
        </el-select>

        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch" class="filter-select">
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>

        <div class="filter-actions">
          <el-button type="info" @click="resetFilters">
            <el-icon><RefreshLeft /></el-icon>
            重置筛选
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="user-table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="batch-actions" v-if="selectedUsers.length > 0">
            <span class="selected-count">已选择 {{ selectedUsers.length }} 项</span>
            <el-button-group>
              <el-button size="small" type="success" @click="batchEnableUsers">
                <el-icon><Check /></el-icon> 批量启用
              </el-button>
              <el-button size="small" type="info" @click="batchDisableUsers">
                <el-icon><Close /></el-icon> 批量禁用
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        :data="paginatedUsers"
        style="width: 100%"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="username" label="用户名" width="150" sortable />
        <el-table-column prop="name" label="姓名" width="150" sortable />
        <el-table-column prop="email" label="邮箱" sortable />
        <el-table-column label="角色" width="200">
          <template #default="scope">
            <el-tag
              v-for="role in scope.row.roles"
              :key="role"
              class="role-tag"
              :type="role === 'admin' ? 'danger' : 'primary'"
              effect="dark"
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'info'" effect="dark">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                size="small"
                type="primary"
                @click="viewUserDetails(scope.row)"
                title="查看详情"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click="editUser(scope.row)"
                :disabled="scope.row.username === 'admin'"
                title="编辑用户"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="confirmDeleteUser(scope.row)"
                :disabled="scope.row.username === 'admin' || scope.row.id === currentUser?.id"
                title="删除用户"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredUsers.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="isEdit ? '编辑用户' : '添加用户'"
      v-model="dialogVisible"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="100px"
        class="user-form"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!isEdit">
              <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="状态">
              <el-switch
                v-model="userForm.is_active"
                active-text="启用"
                inactive-text="禁用"
                inline-prompt
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="角色与权限" name="roles">
            <el-form-item label="角色" prop="roles">
              <div class="role-selection">
                <el-checkbox-group v-model="userForm.roles">
                  <el-card v-for="role in roles" :key="role.id" class="role-card" :class="{ 'selected': userForm.roles.includes(role.name) }">
                    <div class="role-card-header">
                      <el-checkbox :label="role.name">{{ role.name }}</el-checkbox>
                    </div>
                    <div class="role-card-content">
                      <p class="role-description">{{ role.description || '无描述' }}</p>
                      <div class="role-permissions">
                        <el-tag
                          v-for="permission in role.permissions"
                          :key="permission"
                          size="small"
                          type="success"
                          effect="plain"
                          class="permission-tag"
                        >
                          {{ permission }}
                        </el-tag>
                      </div>
                    </div>
                  </el-card>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="detailsDialogVisible"
      width="600px"
      class="user-details-dialog"
    >
      <div v-if="selectedUser" class="user-details">
        <div class="user-header">
          <el-avatar :size="80" :src="selectedUser.avatar || ''">{{ selectedUser.name?.charAt(0) || selectedUser.username?.charAt(0) }}</el-avatar>
          <div class="user-title">
            <h2>{{ selectedUser.name }}</h2>
            <div class="user-subtitle">
              <el-tag v-if="selectedUser.username === 'admin'" type="danger" effect="dark">管理员</el-tag>
              <el-tag v-for="role in selectedUser.roles" :key="role" type="primary" effect="plain" class="role-tag">
                {{ role }}
              </el-tag>
            </div>
          </div>
        </div>

        <el-divider />

        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ selectedUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">
            <el-link type="primary" :href="`mailto:${selectedUser.email}`" target="_blank">{{ selectedUser.email }}</el-link>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedUser.is_active ? 'success' : 'info'" effect="dark">
              {{ selectedUser.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色" :span="2">
            <div class="user-roles">
              <el-tag
                v-for="role in selectedUser.roles"
                :key="role"
                :type="role === 'admin' ? 'danger' : 'primary'"
                effect="dark"
                class="role-tag"
              >
                {{ role }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="权限" :span="2">
            <div class="user-permissions">
              <el-tag
                v-for="permission in userPermissions"
                :key="permission"
                type="success"
                effect="plain"
                class="permission-tag"
              >
                {{ permission }}
              </el-tag>
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <div class="details-actions">
          <el-button type="primary" @click="editUser(selectedUser)" :disabled="selectedUser.username === 'admin'">
            <el-icon><Edit /></el-icon> 编辑用户
          </el-button>
          <el-button type="danger" @click="confirmDeleteUser(selectedUser)" :disabled="selectedUser.username === 'admin' || selectedUser.id === currentUser?.id">
            <el-icon><Delete /></el-icon> 删除用户
          </el-button>
        </div>
      </div>
    </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Setting, Search, RefreshLeft, Check, Close, View, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import PageHeader from '@/components/PageHeader.vue'

// 路由
const router = useRouter()

// 状态
const users = ref([])
const roles = ref([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const detailsDialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref(null)
const authStore = useAuthStore()
const currentUser = computed(() => authStore.user)

// 搜索和筛选
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const selectedUsers = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 表单标签页
const activeTab = ref('basic')

// 选中的用户详情
const selectedUser = ref(null)
const userPermissions = ref([])

// 导航到角色管理
const navigateToRoleManagement = () => {
  router.push('/roles')
}

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  name: '',
  email: '',
  password: '',
  roles: [],
  is_active: true
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择至少一个角色', trigger: 'change' }
  ]
}

// 初始化
onMounted(async () => {
  await fetchUsers()
  await fetchRoles()
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await api.getUsers()
    users.value = response.data.users
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await api.getRoles()
    roles.value = response.data.roles
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索和筛选用户
const filteredUsers = computed(() => {
  let result = users.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user =>
      user.username.toLowerCase().includes(query) ||
      user.name.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query)
    )
  }

  // 角色过滤
  if (roleFilter.value) {
    result = result.filter(user =>
      user.roles.includes(roleFilter.value)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(user =>
      (statusFilter.value === 'active' && user.is_active) ||
      (statusFilter.value === 'inactive' && !user.is_active)
    )
  }

  return result
})

// 分页后的用户列表
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  roleFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 批量启用用户
const batchEnableUsers = async () => {
  if (selectedUsers.value.length === 0) return

  try {
    loading.value = true
    const promises = selectedUsers.value.map(user => {
      if (!user.is_active) {
        return api.updateUser(user.id, { ...user, is_active: true })
      }
      return Promise.resolve()
    })

    await Promise.all(promises)
    ElMessage.success('批量启用用户成功')
    await fetchUsers()
  } catch (error) {
    console.error('批量启用用户失败:', error)
    ElMessage.error('批量启用用户失败')
  } finally {
    loading.value = false
  }
}

// 批量禁用用户
const batchDisableUsers = async () => {
  if (selectedUsers.value.length === 0) return

  // 检查是否包含管理员或当前用户
  const hasAdmin = selectedUsers.value.some(user => user.username === 'admin')
  const hasSelf = selectedUsers.value.some(user => user.id === currentUser.value?.id)

  if (hasAdmin || hasSelf) {
    return ElMessage.warning('不能禁用管理员或当前登录的用户')
  }

  try {
    loading.value = true
    const promises = selectedUsers.value.map(user => {
      if (user.is_active) {
        return api.updateUser(user.id, { ...user, is_active: false })
      }
      return Promise.resolve()
    })

    await Promise.all(promises)
    ElMessage.success('批量禁用用户成功')
    await fetchUsers()
  } catch (error) {
    console.error('批量禁用用户失败:', error)
    ElMessage.error('批量禁用用户失败')
  } finally {
    loading.value = false
  }
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  isEdit.value = false
  resetUserForm()
  activeTab.value = 'basic'
  dialogVisible.value = true
}

// 查看用户详情
const viewUserDetails = async (user) => {
  selectedUser.value = user

  // 获取用户所有权限
  userPermissions.value = []
  const userRoles = roles.value.filter(role => user.roles.includes(role.name))

  // 收集所有权限
  userRoles.forEach(role => {
    role.permissions.forEach(permission => {
      if (!userPermissions.value.includes(permission)) {
        userPermissions.value.push(permission)
      }
    })
  })

  detailsDialogVisible.value = true
}

// 编辑用户
const editUser = (user) => {
  isEdit.value = true
  resetUserForm()

  // 填充表单数据
  userForm.id = user.id
  userForm.username = user.username
  userForm.name = user.name
  userForm.email = user.email
  userForm.roles = user.roles
  userForm.is_active = user.is_active

  // 关闭详情对话框，打开编辑对话框
  detailsDialogVisible.value = false
  activeTab.value = 'basic'
  dialogVisible.value = true
}

// 重置用户表单
const resetUserForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }

  userForm.id = null
  userForm.username = ''
  userForm.name = ''
  userForm.email = ''
  userForm.password = ''
  userForm.roles = []
  userForm.is_active = true
}

// 保存用户
const saveUser = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()

    saving.value = true

    if (isEdit.value) {
      // 更新用户
      const userData = {
        name: userForm.name,
        email: userForm.email,
        roles: userForm.roles,
        is_active: userForm.is_active
      }

      await api.updateUser(userForm.id, userData)
      ElMessage.success('用户更新成功')
    } else {
      // 创建用户
      const userData = {
        username: userForm.username,
        name: userForm.name,
        email: userForm.email,
        password: userForm.password,
        roles: userForm.roles,
        is_active: userForm.is_active
      }

      await api.register(userData)
      ElMessage.success('用户创建成功')
    }

    // 刷新用户列表
    await fetchUsers()
    dialogVisible.value = false
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error(error.response?.data?.message || '保存用户失败')
  } finally {
    saving.value = false
  }
}

// 确认删除用户
const confirmDeleteUser = (user) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      deleteUser(user.id)
      // 如果是从详情对话框删除，关闭详情对话框
      if (detailsDialogVisible.value) {
        detailsDialogVisible.value = false
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 删除用户
const deleteUser = async (userId) => {
  loading.value = true
  try {
    await api.deleteUser(userId)
    ElMessage.success('用户删除成功')
    await fetchUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error(error.response?.data?.message || '删除用户失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.user-management-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.user-management-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 使用共享的 PageHeader 组件样式 */

.role-btn {
  background-color: #67c23a;
  border-color: #67c23a;
}

.role-btn:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 搜索和筛选区域 */
.filter-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 180px;
}

.filter-actions {
  margin-left: auto;
}

/* 用户列表样式 */
.user-table-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  font-size: 14px;
  color: #606266;
}

.role-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

/* 用户表单样式 */
.user-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.role-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
}

.role-card {
  width: 100%;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  cursor: pointer;
}

.role-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.role-card-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.role-card-content {
  padding: 10px;
}

.role-description {
  margin: 0 0 10px;
  font-size: 13px;
  color: #606266;
}

.role-permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.permission-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

/* 用户详情样式 */
.user-details {
  padding: 10px;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.user-title h2 {
  margin: 0 0 10px;
  font-size: 20px;
}

.user-subtitle {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.user-roles, .user-permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.details-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
